package pers.elonnsu.springbootmall.service.impl;

import org.springframework.stereotype.Service;
import pers.elonnsu.springbootmall.exception.MallException;
import pers.elonnsu.springbootmall.exception.MallExceptionEnum;
import pers.elonnsu.springbootmall.model.dao.UserMapper;
import pers.elonnsu.springbootmall.model.pojo.User;
import pers.elonnsu.springbootmall.service.UserService;
import pers.elonnsu.springbootmall.util.MD5Utils;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void register(String userName, String password) throws MallException {
        // 用户名重名排查，禁止重名
        User selectedUser = userMapper.selectByUserName(userName);

        if (selectedUser != null) {
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }

        // 写入数据库
        User user = new User();
        user.setUsername(userName);
        try {
            user.setPassword(MD5Utils.getMD5String(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int count = userMapper.insertSelective(user);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String userName, String password) throws MallException {
        String md5Password = null;
        try {
            md5Password = MD5Utils.getMD5String(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        User loginUser = userMapper.selectLoginUser(userName, md5Password);

        if (loginUser == null) {
            throw new MallException(MallExceptionEnum.PASSWORD_WRONG);
        }
        return loginUser;
    }

    @Override
    public void updateUser(User user) throws MallException {
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count > 1) {
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean isAdminRole(User user) {
        // 1 为普通用户，2 为管理员
        return user.getRole().equals(2);
    }
}
